package cj.web.sc.controllers;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.weixin.HttpsWenXinUtil;
import cj.web.cc.controllers.BaseController;
import cj.web.sc.dao.GoodsDAO;
import cj.web.uc.dao.LoginDAO;

@Path("goods")
public class GoodsController extends BaseController{
	@Autowired
	private GoodsDAO goodsDao;
	@Autowired
	private LoginDAO memberDAO;
	
	@Get("homeCode")  //商品列表
	public String homeCode(Model model,@Param("code")String code,
			HttpServletResponse response){
		String openId = HttpsWenXinUtil.retOpenId(code,APPID,APPSECRET);
		//		String openId = "1111";
		
		setCookie(response, "openId", openId);
		
		return "r:home";
	}
	
	@Get("home")  //商品列表
	public String home(Model model,@Param("state")String state, 
			HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String, String> config = getConfigSign(request);
		model.add("Config",config);
		
		model.add("Title", "公司名称");
		model.add("Desc", "公司名称");
		model.add("LinkURL", oauth_start+homeCode+oauth_end);
		
		//------------------------------获取传递过来的game 和 参赛证号
		String urlGameId = "";
		String urlCode = "";
		if(state!=null && !"".equals(state)){
			urlGameId = state.split(URLPARAMS)[0].toString();
			urlCode = state.split(URLPARAMS)[1].toString();
		}
		setCookie(response, "urlGameId", urlGameId);
		setCookie(response, "urlCode", urlCode);
		//------------------------------获取传递过来的game 和 参赛证号
				
		return "/views/mall/home.vm";
	}
	
	@Post("list")  //商品列表
	public String list(){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> objs = goodsDao.goodsList();
		
		jo.put("objs", objs);
		return "@" + jo.toString();
	}
	
	@Get("itemsCode")
	public String itemsCode(Model model,@Param("code")String code, @Param("state")int goodsId, HttpServletResponse response){
		String openId = HttpsWenXinUtil.retOpenId(code,APPID,APPSECRET);
		setCookie(response, "openId", openId);
		return "r:items?id=" + goodsId;
	}
	
	@Get("items") //商品多属性详情
	public String items(Model model, @Param("id")int goodsId, HttpServletRequest request) throws Exception{
		List<Map> goodsObj = goodsDao.getGoodsById(goodsId);
		List<Map> itemObjs = goodsDao.getVltItemsByGoodsId(goodsId);
		if(goodsObj != null && goodsObj.size() > 0 && 
				itemObjs!=null && itemObjs.size() > 0){
			for(Map map : itemObjs){
				map.put("propValueNames", map.get("propValueNames").toString().replaceAll(",", ""));
			}
			List<Map> banner = goodsDao.getBannerByGoodsId(goodsId);
			
			model.add("Goods",goodsObj.get(0));
			model.add("Items",itemObjs);
			model.add("Banner",banner);
			
			Map<String, String> config = getConfigSign(request);
			model.add("Config",config);
			
			model.add("Title", "公司名称-" + goodsObj.get(0).get("title").toString());
			model.add("Desc", getShareDesc(goodsObj.get(0).get("descs").toString()));
			model.add("LinkURL", oauth_start+"http://signup.whccwh.com/goods/itemsCode&response_type=code&scope=snsapi_base&state=" + goodsId + "#wechat_redirect");
			return "/views/mall/items.vm";
		}
		else{
			model.add("warning", "该商品已下架");
			return "/views/mall/orderNothing.vm";
		}
		
	}
	
	@Get("itemCode") //众筹商品详情
	public String itemCode(Model model,@Param("code")String code, @Param("state")int goodsId, HttpServletResponse response){
		String openId = HttpsWenXinUtil.retOpenId(code,APPID,APPSECRET);
		setCookie(response, "openId", openId);
		return "r:item?id=" + goodsId;
	}
	
	@Get("item") //众筹商品详情
	public String item(Model model, @Param("id")int goodsId, HttpServletRequest request) throws Exception{
		List<Map> goodsObj = goodsDao.getGoodsById(goodsId);
		List<Map> itemObjs = goodsDao.getItemsByGoodsId(goodsId);
		
		if(goodsObj != null && goodsObj.size() > 0 && 
				itemObjs!=null && itemObjs.size() > 0){
			for(Map map : itemObjs){
				map.put("propValueNames", map.get("propValueNames").toString().replaceAll(",", ""));
			}
			List<Map> banner = goodsDao.getBannerByGoodsId(goodsId);
			
			model.add("Goods",goodsObj.get(0));
			model.add("Item",itemObjs.get(0));
			model.add("Banner",banner);
			
			Map<String, String> config = getConfigSign(request);
			model.add("Config",config);
			
			model.add("Title", "公司名称-" + goodsObj.get(0).get("title").toString());
			model.add("Desc", getShareDesc(goodsObj.get(0).get("descs").toString()));
			model.add("LinkURL", oauth_start+"http://signup.whccwh.com/goods/itemCode&response_type=code&scope=snsapi_base&state=" + goodsId + "#wechat_redirect");
			return "/views/mall/item.vm";
		}
		else{
			model.add("warning", "该商品已下架");
			return "/views/mall/orderNothing.vm";
		}
		
	}
	
	@Post("intoCart")  //加入购物车
	public String intoCart(@Param("goodsId")int goodsId, @Param("sellerId")int sellerId,@Param("goodsItemId")int goodsItemId,
			@Param("count")int count, @Param("retPg")String retPg, HttpServletRequest request, HttpServletResponse response){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		if( isLogin(request) ){
			List<Map> goodsItem = goodsDao.getGoodsItemById(goodsItemId);
			
			if(goodsItem != null && goodsItem.size() > 0 ){   //验证库存
				int inventory = Integer.parseInt(goodsItem.get(0).get("inventory").toString());
				if(inventory < count){
					jo.put("rtnMsg", "库存不足");
					jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
					return "@" + jo.toString();
				}
				else{
					String phone = getCookieValueByName(request, "phone");
					int buyerId = memberDAO.getBuyerId(phone);
					
					List<Map> Obj = goodsDao.isInCart(buyerId, goodsItemId);
					
					if(Obj != null && Obj.size() > 0){
						int origCnt = Integer.parseInt(Obj.get(0).get("count").toString());
						if( inventory < count + origCnt ){
							jo.put("rtnMsg", "库存不足");
							jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
							return "@" + jo.toString();
						}
						else{
							goodsDao.updateCart(count,buyerId,goodsItemId);
						}
					}
					else{
						goodsDao.insertCart(buyerId, sellerId, goodsItemId, count, phone);
					}
				}
			}
			else{
				jo.put("rtnMsg", "该商品已下架");
				jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
				return "@" + jo.toString();
			}
		}
		else{
			String returnPage = "/goodsPc/" + retPg + "?id=" + goodsId;
			setCookie(response, "returnPage", returnPage);//订单
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
			return "@" + jo.toString();
		}
		
		return "@" + jo.toString();
	}
	
	private String getShareDesc(String html) {
		Document doc = Jsoup.parse(html);
        Elements eles = doc.getElementsByTag("p");
        
        String shareDesc = "";
        
        if(null != eles &&  eles.size() > 0 ){
        	String txt = eles.get(0).text();
        	if( null != txt && txt.length() > 0 ){
        		shareDesc = txt;
        	}
        }
        
		return shareDesc;
	}
	
}
